package com.chenfan.magic.config.aspect;

import com.chenfan.magic.annation.DbType;
import com.chenfan.magic.config.DatabaseContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author liuming
 * @date 2021-07-19 16:49
 */
@Component
@Aspect
@Slf4j
public class DbTypeAspect {

    @Pointcut("@annotation(com.chenfan.magic.annation.DbType)")
    private void pointcut() {
    }

    @Before(value = "pointcut()")
    public void before(JoinPoint joinpoint) {
        Method method = ((MethodSignature) joinpoint.getSignature()).getMethod();
        DbType dbType = AnnotationUtils.findAnnotation(method, DbType.class);
        DatabaseContextHolder.setDatabaseType(dbType.type());
    }

    @After(value = "pointcut()")
    public void after(JoinPoint joinPoint) {
        DatabaseContextHolder.remove();
    }

    @AfterThrowing(value = "pointcut()")
    public void afterThrowing(JoinPoint joinPoint) {
        DatabaseContextHolder.remove();
    }

}
